<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="(form.platform_name || '') + (form.platform_id ? '平台编辑' : '平台信息添加')" v-model="visible" align-center width="800px"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :label-width="140">
      <div class="grid grid-cols-1 gap-x-3">
        <el-form-item label="平台名称" prop="platform_name" :rules="[{ validator, trigger: 'blur' }]">
          <div class="flex w-full">
            <el-input v-model.lazy="form.platform_name" placeholder="请输入" :maxlength="128" show-word-limit />
            <div class="whitespace-nowrap ml-2">只允许汉字、字母、下划线和数字</div>
          </div>
        </el-form-item>
        <el-form-item label="平台代码" prop="platform_code" :rules="[{ validator: validator1, trigger: 'blur' }]">
          <div class="flex w-full">
            <el-input v-model.lazy="form.platform_code" placeholder="请输入" :maxlength="64" show-word-limit :disabled="!!form.platform_id" />
            <div class="whitespace-nowrap ml-2">只允许小写字母、下划线和数字</div>
          </div>
        </el-form-item>
        <div class="grid grid-cols-2 gap-x-3">
          <el-form-item label="平台Logo">
            <template #label>
              平台Logo
              <span class="text-gray-400 ml-2">
                支持大小：2M 扩展名：.jpg .jpeg .png
              </span>
            </template>
            <ImageUpload v-model="form.platform_logo" :limit="1" :disabled="form.shop_id" :fileSize="2" :fileType="['png', 'jpg', 'jpeg']" :isShowTip="false">
            </ImageUpload>
          </el-form-item>
          <div class="grid grid-cols-2 gap-x-3">
            <el-form-item label="启用状态">
              <el-switch v-model="form.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value='1' :inactive-value='2' />
            </el-form-item>
            <el-form-item label="API对接状态">
              <el-switch v-model="form.api_status" inline-prompt active-text="启用" inactive-text="禁用" :active-value='1' :inactive-value='2' />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <template v-if="form.platform_id">
      <el-button type="primary" class="mb-2" @click="() => addSiteRef.open({platform_id: form.platform_id})">添加站点</el-button>
      <vxe-table :data="data" :loading="loadings.data">
        <vxe-column title="站点名称" field="site_name"></vxe-column>
        <vxe-column title="站点图标">
          <template #default="{row}">
            <VImage v-if="row.site_logo" :src="row.site_logo[0]" />
          </template>
        </vxe-column>
        <vxe-column title="站点简称" field="site_abbrev"></vxe-column>
        <vxe-column title="站点代码" field="site_code"></vxe-column>
        <vxe-column title="站点国家" field="site_country_name"></vxe-column>
        <vxe-column title="币种" field="currency_name"></vxe-column>
        <vxe-column title="站点语言" field="language_name"></vxe-column>
        <vxe-column title="站点链接" field="site_link"></vxe-column>
        <vxe-column title="操作">
          <template #default="{row}">
            <el-button link @click="() => addSiteRef.open(row)">编辑</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </template>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
    <AddSite ref="addSiteRef" :options="options" @success="query" />
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import ImageUpload from '@/components/ImageUpload'
import AddSite from './AddSite'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const success = ref(false)
let loadings = reactive({})
const addSiteRef = ref()

// 表单处理
const formRef = ref()
const form = ref({})

const validator = (rule, value, cb) => {
  if (!value) cb(new Error('不能为空'))
  if(!/^[\u4e00-\u9fa5a-zA-Z0-9_]+$/.test(value)) cb(new Error('只允许汉字、字母、下划线和数字'))
  cb()
}
const validator1 = (rule, value, cb) => {
  if (!value) cb(new Error('不能为空'))
  if (!/^[a-z0-9_]+$/.test(value)) cb(new Error('只允许小写字母、下划线和数字'))
  cb()
}

const platform_id = ref()
const data = ref([])
const query = () => {
  loadings.data = true
  api.siteQuery({ platform_id: platform_id.value }).then(res => {
    data.value = res.data
  }).finally(() => {
    loadings.data = false
  })
}

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {}
  platform_id.value = id
  loadings = reactive({})
  success.value = false
  visible.value = true
  formRef?.value?.clearValidate()
  // 编辑
  if (id) {
    const res = await api.detail({ platform_id: id })
    form.value = res.data
    console.log('id', id)
    query()
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}
// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  api[form.value.platform_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    success.value = true
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>